package com.xuetang9.demo.ssm.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xuetang9.demo.ssm.domain.Resource;
import com.xuetang9.demo.ssm.domain.vo.TreeNodeVO;
import com.xuetang9.demo.ssm.service.ResourceService;

@Controller
public class IndexController {
	
	@Autowired
	private ResourceService resourceService;
	

	@RequestMapping(path="/index")
	public String index(ModelMap model,HttpSession session) {
		// 获取菜单
		List<Resource> resources = resourceService.listAll();
		// 把菜单的集合数据转换成树形结构
		List<TreeNodeVO<Resource>> tree = bulidTree(resources);
		// 把树形结构的菜单数据保存到model中
//		model.put("menus", tree);
		session.setAttribute("menus", tree);
		// 跳转页面
		return "index";
	}
	
	
	private List<TreeNodeVO<Resource>> bulidTree(List<Resource> resources){
		// 创建一个树形节点的集合
		List<TreeNodeVO<Resource>> tree = new ArrayList<TreeNodeVO<Resource>>();
		// 找到根节点
		for (Resource resource : resources) {
			if(resource.getPid() == 0) {
				// 创建节点
				TreeNodeVO<Resource> node = new TreeNodeVO<Resource>();
				node.setItem(resource);
				// 添加到树中
				tree.add(node);
				// 找到当前节点的子节点
				findChildren(node,resources);
				
			}
		}
		return tree;
	}


	private void findChildren(TreeNodeVO<Resource> node, List<Resource> resources) {
		for (Resource resource : resources) {
			if(resource.getPid() == node.getItem().getId()) {
				// 创建子节点
				TreeNodeVO<Resource> childNode = new TreeNodeVO<Resource>();
				childNode.setItem(resource);
				// 添加到父节点中
				if(node.getChildren() == null) {
					node.setChildren(new ArrayList<TreeNodeVO<Resource>>());
				}
				node.getChildren().add(childNode);
				
				// 查找当前节点的子节点
				findChildren(childNode, resources);
			}
		}
		
	}
	
	
	
}
